package com.cqz.action;

import com.cqz.dao.BookInfo;
import com.cqz.dao.OrderInfo;
import com.cqz.dao.TagInfo;
import com.cqz.dao.UserInfo;
import com.cqz.services.BookService;
import com.cqz.services.OrderService;
import com.cqz.services.UserService;
import com.cqz.tools.Tools;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;

@Controller
public class InsertAction {

    @Autowired
    private BookService bookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    /**
     * 添加书籍信息
     * @param httpSession
     * @param bookInfo
     * @param tagInfo
     * @param bprice
     * @return
     */
    @RequestMapping("insertBookInfoAction")
    public String insertBookInfoAction(HttpSession httpSession,BookInfo bookInfo,TagInfo tagInfo,String bprice){

        if(Tools.isNull(bookInfo.getBname())){
            httpSession.setAttribute("bnameerror","书名不能为空");
            return "redirect:adminAction?whichPanel="+3;
        }
        if(Tools.isNull(bookInfo.getBauthor())){
            httpSession.setAttribute("bauthorerror","作者名不能为空");
            return "redirect:adminAction?whichPanel="+3;
        }
        if(Tools.isNull(bookInfo.getBscore())){
            httpSession.setAttribute("bscoreerror","评分不能为空或小于0");
            return "redirect:adminAction?whichPanel="+3;
        }
        if(Tools.isNull(bprice)){
            httpSession.setAttribute("bpriceerror","价格不能为空或小于0");
            return "redirect:adminAction?whichPanel="+3;
        }else {
            bookInfo.setBprice(new BigDecimal(bprice));
        }
        if(bookInfo.getBnum()<0){
            httpSession.setAttribute("bnumerror","库存不能为负");
            return "redirect:adminAction?whichPanel="+3;
        }
        if(Tools.isNull(bookInfo.getBurl())){
            httpSession.setAttribute("burlerror","图片路径不能为空");
            return "redirect:adminAction?whichPanel="+3;
        }

        String []tags=new String[6];
        tags[0]=tagInfo.getTag1();tags[1]=tagInfo.getTag2();tags[2]=tagInfo.getTag3();
        tags[3]=tagInfo.getTag4();tags[4]=tagInfo.getTag5();tags[5]=tagInfo.getTag6();
        boolean flag=bookService.addBookAndTag(bookInfo,tags);
        if(flag==false){
            httpSession.setAttribute("berror","录入失败");
            return "redirect:adminAction?whichPanel="+3;
        }else {
            return "redirect:adminAction?whichPanel="+3;
        }
    }

    /**
     * 添加购物车
     * @param user_id
     * @param bookId
     * @return
     */
    @RequestMapping(value = "insertShopTrolleyAction",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String insertShopTrolleyAction(String user_id,String bookId){
        String result = orderService.addRecord(user_id,bookId);
        String addResult="";
        JSONObject jsonObject= new JSONObject();
        if(result.equals("success")) {
            jsonObject.put("code",true);
            addResult = "成功添加至购物车！";

        }
        else if(result.equals("exist already")) {
            jsonObject.put("code",false);
            addResult = ("已存在于购物车中！");
        }
        else {
            jsonObject.put("code",false);
            addResult = "error";
        }

        jsonObject.put("message",addResult);
        return jsonObject.toString();
    }

    /**
     * 生成订单界面
     * @param model
     * @param bid
     * @return
     */
    @RequestMapping("generateOrderAction")
    public String generateOrderAction(Model model,String bid){
        int id=Integer.parseInt(bid);
        BookInfo bookInfo=bookService.getBookById(id);
        model.addAttribute("bookInfo",bookInfo);
        model.addAttribute("pricePerBook",bookInfo.getBprice());
        return "purchase";
    }

    /**
     * 添加订单
     * @param totalPrice
     * @param bid
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "insertPaymentAction",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String insertPaymentAction(String totalPrice,String bid,HttpSession httpSession){
        int uid=(Integer) httpSession.getAttribute("uid");
        UserInfo userInfo=userService.findUser(uid);

        JSONObject jsonObject= new JSONObject();
        String addResult="";
        BigDecimal total=new BigDecimal(totalPrice);
        if(Tools.isNull(userInfo.getUaddress())){
            jsonObject.put("code",false);
            addResult="请确认收货地址";
        }else if(userInfo.getUamount().compareTo(total)==-1){
            jsonObject.put("code",false);
            addResult="余额不足";
        }else {
            userInfo.setUamount(userInfo.getUamount().subtract(total));
            BookInfo bookInfo=bookService.getBookById(Integer.parseInt(bid));
            int num=total.divide(bookInfo.getBprice()).intValue();
            if(num>bookInfo.getBnum()){
                jsonObject.put("code",false);
                addResult="库存不足";
            }else {
                bookInfo.setBnum(bookInfo.getBnum()-num);
                OrderInfo orderInfo=new OrderInfo();
                orderInfo.setOstate("已付款");
                orderInfo.setOprice(bookInfo.getBprice());
                orderInfo.setOamount(total);
                long l = System.currentTimeMillis();
                //new日期对象
                Date date = new Date(l);
                orderInfo.setOdate(date);
                orderInfo.setOnum(num);
                orderInfo.setUid(uid);
                orderInfo.setBid(Integer.parseInt(bid));
                boolean f1=userService.updateByUid(userInfo);
                boolean f2=orderService.addPayment(orderInfo);
                boolean f3=bookService.updateBookInfo(bookInfo);
                if(f1&&f2){
                    jsonObject.put("code",true);
                    addResult="支付成功";
                }else {
                    jsonObject.put("code",false);
                    addResult="支付失败";
                    httpSession.setAttribute("money",userInfo.getUamount());
                }
            }


        }
        jsonObject.put("message",addResult);
        return jsonObject.toString();
    }
}
